#!/usr/bin/env powershell

$argprefixs = @(
    "--depth",
    "--branch",
    "--origin",
    "--reference",
    "--upload-pack",
    "--config",
    "-c"
)

$zargs = New-Object -TypeName System.Collections.ArrayList
$newargs = "clone "
for ($i = 1; $i -lt $args.Count; $i++) {
    [string]$arg = $args[$i]
    if ($arg.Contains(" ") -or $arg.Contains("\t")) {
        $newargs += "`"$arg`" "
    }
    else {
        $newargs += "$arg "
    }
    if ($arg.StartsWith("-")) {
        if ($argprefixs.Contains($arg)) {
            $i++
        }
        Continue
    }
    $zargs += $arg
}

$Url = $zargs[0]
$sec = [System.IO.Path]::DirectorySeparatorChar
if ($zargs.Length -eq 1 ) {
    $dir = Split-Path -Leaf $Url
    if ($dir.EndsWith(".git")) {
        $dir = $dir.Remove($dir.Length - 4, 4)
    }
    $Path = "$PWD/$dir"
    $Parent = $Path
}
else {
    $xpath = $zargs[1]
    if ($xpath -eq ".") {
        $Path = $PWD
        $Parent = Split-Path $Path
        Set-Location "$Parent"
    }
    elseif ($xpath.Contains($sec)) {
        $xparent = Split-Path $xpath
        $leaf = Split-Path -Leaf $xpath
        $Parent = Resolve-Path $xparent -ErrorAction SilentlyContinue
        if (!$?) {
            Write-Host -ForegroundColor Red "$($error[0])"
            exit 1
        }
        $Path = "$Parent$sec$leaf"
    }
    else {
        $Path = "$PWD$sec$xpath"
    }
}

Write-Host "URL $($zargs[0]) Path: $Path"